package com.tuanzi.loan.web.bean.family.user;

import com.google.common.collect.Lists;
import com.tuanzi.loan.business.constants.DictionaryCode;
import com.tuanzi.loan.business.entity.user.LoanUserAgreement;
import com.tuanzi.loan.business.service.user.LoanUserAgreementService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.web.configuration.JSFInfoBean;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import java.util.List;

/**
 * @Author: chenweijun
 * @Date: 2019/9/26 14:50
 */

@Data
@Debug
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
@Slf4j
public class LoanUserAgreementInfoBean extends JSFInfoBean<LoanUserAgreement> {

    @Autowired
    private LoanUserAgreementService loanUserAgreementService;

    List<String> selectedParentProductIds;

    @PostConstruct
    private void init() {
        $ = new LoanUserAgreement();

        LoanUserAgreement topLoanUserAgreement =  loanUserAgreementService.findTopOne();
        if(topLoanUserAgreement != null){
            $.setRuleId(topLoanUserAgreement.getRuleId() + 1);
        }else{
            $.setRuleId(1);
        }
        changeStatusToAdd();
    }

    public void onSave(){
        try {
             LoanUserAgreement loanUserAgreement = loanUserAgreementService.findOneByRuleId($.getRuleId());
             if(loanUserAgreement != null){
                 addErrorMessage("协议ID已存在");
                 return;
             }
            loanUserAgreementService.save($, selectedParentProductIds);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        addSuccessfullyMessage();
        changeStatusToView();
    }

    @Override
    protected List<String> getDictionaryCodes() {
        return Lists.newArrayList(DictionaryCode.LARGE_COMMON_PRODUCT);
    }
}
